package com.ewzj.bigdata.mvp.presenter

import android.Manifest
import android.app.Application
import android.support.v4.app.Fragment
import android.support.v4.view.ViewPager
import android.support.v7.app.AppCompatActivity
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.ewzj.bigdata.app.config.AppKey
import com.ewzj.bigdata.app.config.AppLocationListener
import com.ewzj.bigdata.app.extensions.DelegatesExt
import com.ewzj.bigdata.app.utils.Apputils
import com.ewzj.bigdata.app.utils.RxUtils
import com.ewzj.bigdata.mvp.contract.MainContract
import com.ewzj.bigdata.mvp.model.rspbean.BaseData
import com.ewzj.bigdata.mvp.model.rspbean.CityBean
import com.ewzj.bigdata.mvp.model.rspbean.CitySearchBean
import com.ewzj.bigdata.mvp.ui.adapter.TabAdapter
import com.ewzj.bigdata.mvp.ui.fragment.HomeFragment
import com.ewzj.bigdata.mvp.ui.fragment.MineFragment
import com.ewzj.bigdata.mvp.ui.fragment.NewFragment
import com.ewzj.bigdata.mvp.ui.fragment.VideoFragment
import com.google.gson.Gson
import com.gyf.barlibrary.ImmersionBar
import com.jess.arms.mvp.BasePresenter
import com.jess.arms.utils.UiUtils
import com.tbruyelle.rxpermissions2.RxPermissions
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.activity_main_tab.*
import me.jessyan.rxerrorhandler.core.RxErrorHandler
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber
import javax.inject.Inject


/**
 * author:zhangjing
 * 作用:
 * return:
 */
class MainPresenter @Inject constructor(val mGson: Gson, val mErrorHandler: RxErrorHandler, val application: Application, view: MainContract.View, model: MainContract.Model)
    :BasePresenter<MainContract.Model,MainContract.View>(model,view){
    val fragments= listOf<Fragment>(HomeFragment.newInstance(),NewFragment.newInstance(),VideoFragment.newInstance(),MineFragment.newInstance())
    val context=mRootView as AppCompatActivity;
    val mLocationClient :LocationClient by lazy { LocationClient(application) }
    var adapter:TabAdapter=TabAdapter(fragments,context.supportFragmentManager)
    val mImmersionBar by lazy { ImmersionBar.with(context) }
    var savedcity:String by DelegatesExt.preference(application,AppKey.LOCATION_CITY,"")
    fun initViewPager(viewPager: ViewPager):Unit{
        viewPager.adapter=adapter
    }
    fun initstatusbar(){
        mImmersionBar.init()
    }
    fun initBdLocation(){
        Apputils.Utils.initLocation(mLocationClient)
        mLocationClient.registerLocationListener(AppKey.locationListener)
        AppKey.locationListener.locationlistener=object : AppLocationListener.LoctionListener{
            override fun locationComplete(location: BDLocation) {
                AppKey.bdLocation=location
                if (location==null){
                    var citybean = CityBean.ListEntity()
                    citybean.setLat(30.576279)
                    citybean.setLon(104.071216)
                    AppKey.bdLocation!!.latitude=30.576279
                    AppKey.bdLocation!!.longitude=104.071216
                    citybean.setCity("成都市")
                    citybean.setLocatecity("定位失败")
                    citybean.setId("63")
                    savedcity=mGson.toJson(citybean)
                    return
                }
                if (savedcity.isNullOrEmpty()){
//                    第一次进入还没有保存上一次的城市信息
                    mModel.getCityByname(location.city).compose(RxUtils.applySchedulers(mRootView))
                            .subscribe(object :ErrorHandleSubscriber<BaseData<CitySearchBean>>(mErrorHandler){
                                override fun onNext(citySearchBeanBaseData: BaseData<CitySearchBean>) {
                                    if (citySearchBeanBaseData.data!!.getList().size == 0){
                                        run {
                                        val listEntity = CityBean.ListEntity()
                                        listEntity.setCity("成都市")
                                        listEntity.setId("63")
                                        listEntity.setFirst("c")
                                        listEntity.setLocatecity(location.city)
                                        listEntity.setLat(location.latitude)
                                        listEntity.setLon(location.longitude)
                                         savedcity=mGson.toJson(listEntity)
                                    }
                                }else{
                                        val listEntity = citySearchBeanBaseData!!.data!!.list[0]
                                        val cityBean = CityBean.ListEntity()
                                        cityBean.city = listEntity.getCity()
                                        cityBean.id = listEntity.getId()
                                        cityBean.locatecity = location.city
                                        cityBean.adress = location.address.city + "  " + location.address.district
                                        cityBean.district = location.district
                                        cityBean.lat = location.latitude
                                        cityBean.lon = location.longitude
                                        savedcity=mGson.toJson(cityBean)
                                        try{
                                            (fragments[0] as HomeFragment).locationCity(listEntity.getCity(),true)
                                        }catch (e :Exception){
                                            e.printStackTrace()
                                        }

                                    }
                                }

                            })
                }else{
                    //  已经保存保存上一次的城市信息
                }
            }
        }
        RxPermissions(context).request(Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe(Consumer { t -> if (t){
                    if (AppKey.bdLocation==null){
                        mLocationClient.start()
                    }

                }else{
                    var citybean = CityBean.ListEntity()
                    citybean.setLat(30.576279)
                    citybean.setLon(104.071216)
                    citybean.setCity("成都市")
                    citybean.setLocatecity("定位失败")
                    citybean.setId("63")
                    savedcity=mGson.toJson(citybean)
                    UiUtils.SnackbarText("你已拒绝定位")
                } })


    }

    fun stop(){
        mLocationClient.stop()
    }

    fun changeStatusbar(pos:Int){
        when(pos){
            0->(fragments[0] as HomeFragment).setStatusBar(mImmersionBar)
            1->(fragments[1] as NewFragment).setStatusBar(mImmersionBar)
            2->(fragments[2] as VideoFragment).setStatusBar(mImmersionBar)
            3->(fragments[3] as MineFragment).setStatusBar(mImmersionBar)
//            3->fragments[3].activity;
        }
    }
}